package com.pf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.pf.mapper.OrderMapper;
import com.pf.mapper.StockMapper;
import com.pf.mapper.entity.Order;
import com.pf.mapper.entity.Stock;
import com.pf.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Date;

/**
 * @author PanFei
 * @date 2021/5/20 21:12
 * @Version 1.0
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private OrderMapper orderMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void killGoodsSimple(Integer id) {
        // 1.查看是否还有库存
        Stock stock = stockMapper.selectOne(new LambdaQueryWrapper<Stock>()
                .eq(Stock::getId, id)
        );
        if (stock != null && stock.getCount() <= 0) {
            throw new RuntimeException("库存不足！！！");
        }
        // 2.减库存
        stock.setCount(stock.getCount() - 1);
        stockMapper.updateById(stock);

        // 3.新增订单
        Order order = Order.builder().name(stock.getName()).goodsId(stock.getId()).createDate(new Date()).build();
        orderMapper.insert(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void killWithCAS(Integer id) {
        // 1.查看是否还有库存
        Stock stock = stockMapper.selectOne(new LambdaQueryWrapper<Stock>()
                .eq(Stock::getId, id)
        );
        if (stock != null && stock.getCount() <= 0) {
            throw new RuntimeException("库存不足！！！");
        }

        // 2.减库存
        int flag = stockMapper.update(null, new LambdaUpdateWrapper<Stock>()
                .eq(Stock::getId, id)
                .eq(Stock::getVersion, stock.getVersion())
                .set(Stock::getCount, stock.getCount() - 1)
                .set(Stock::getVersion, stock.getVersion() + 1)
        );
        if (flag == 1) {
            // 3.下单
            Order order = Order.builder().name(stock.getName()).goodsId(stock.getId()).createDate(new Date()).build();
            orderMapper.insert(order);
        }
    }


    /**
     * 初始化stock表记录
     */
    @PostConstruct
    public void initStockData() {
        stockMapper.insert(Stock.builder()
                .name("IPhone")
                .count(20)
                .version(1)
                .build()
        );
    }
}
